package org.fast.develop.logicflow.ws.manager;

import lombok.extern.slf4j.Slf4j;
import org.fast.develop.logicflow.runtime.ws.IWsSessionStore;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WsSessionStore implements IWsSessionStore {
    /**
     * 保存连接 session 的地方
     */

    private ConcurrentHashMap<String, Session> webSockets = new ConcurrentHashMap<>();

    /**
     * 添加 session
     *
     * @param key
     * @param session
     */
    public void put(String key, Session session) {
        // 添加 session
        webSockets.put(key, session);
    }

    /**
     * 删除 session 返回 session
     *
     * @param key
     * @return
     */
    public Session remove(String key) {
        // 删除 session
        return webSockets.remove(key);
    }

    /**
     * 删除并同步关闭连接
     *
     * @param key
     */
    public void removeAndClose(String key) {
        Session session = remove(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得 session
     *
     * @param key
     * @return
     */
    public Session get(String key) {
        // 获得 session
        return webSockets.get(key);
    }

    public Collection<Session> getSessions(){
        return webSockets.values();
    }
}
